import { defineEventHandler, readBody, getRequestHeaders } from 'h3'
import { execute } from '../utils/db'
import type { H3Event } from 'h3'
import { ResponseCode, sendSuccessResponse, sendErrorResponse } from '~/server/utils/response'


export default defineEventHandler(async (event: H3Event) => {
  const body = await readBody(event)
  const headers = getRequestHeaders(event)

  // 验证必填字段
  if (!body.name || !body.contactInfo || !body.requirements) {
    // throw createError({
    //   statusCode: 400,
    //   message: '姓名、联系方式和需求内容为必填项'
    // })
    return sendErrorResponse(event, ResponseCode.BAD_REQUEST, '姓名、联系方式和需求内容为必填项')
  }

  // 获取客户端IP和User-Agent
  const ip = headers['x-forwarded-for'] || headers['x-real-ip'] || event.node.req.socket.remoteAddress
  const userAgent = headers['user-agent']

  try {
    // 插入数据库
    const sql = `
      INSERT INTO contact_submissions 
      (name, contact_info, requirements, ip_address, user_agent)
      VALUES (?, ?, ?, ?, ?)
    `
    await execute(sql, [
      body.name,
      body.contactInfo,
      body.requirements,
      ip,
      userAgent
    ])
    return sendSuccessResponse(event, {
      status: 'success',
    }, '提交成功，我们会尽快与您联系！')
  } catch (error: any) {
    console.error('联系表单提交失败:', error)
    // throw createError({
    //   statusCode: 500,
    //   message: '提交失败，请稍后再试'
    // })
    return sendErrorResponse(event, ResponseCode.INTERNAL_ERROR, error?.message || '提交失败，请稍后再试')

  }
})